package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"im/app/models/form/message"
	validator2 "im/app/models/validator"
	"im/app/services"
	"im/app/util/response"
	"time"
)

type MessageController struct {

}

// 保存消息
func (m *MessageController) Add(c *gin.Context) {
	inputs := message.MessageControllerAdd{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		//设置转换器
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ms := services.MessageService{}
	messages,err := ms.AddRabbit(&inputs)
    if err != nil {
	   response.ReturnJsonOk(c, err.Error())
	   return
    }

   response.ReturnJsonOk(c, "成功", messages)
}

// 消息ack
func (m *MessageController) Ack(c *gin.Context) {
	inputs := message.MessageControllerAck{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		//设置转换器
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ms := services.MessageService{}
	err = ms.Ack(&inputs)
	if err != nil {
		response.ReturnJsonOk(c, err.Error())
		return
	}

	response.ReturnJsonOk(c, "成功", "")
}

// 获取离线消息
func (m *MessageController) GetOutLiveMsg(c *gin.Context) {
	inputs := message.MsgCtlOutLiveMsg{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		//设置转换器
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	ms := services.MessageService{}
	where := make([]map[string]interface{}, 0)
	w1 := map[string]interface{}{ "dst_id = ?": inputs.UserId }
	w2 := map[string]interface{}{ "is_r = ?": 0 }
	w3 := map[string]interface{}{ "created_at < ?": time.Now().Unix() }
	where = append(where, w1)
	where = append(where, w2)
	where = append(where, w3)
	messagea := ms.List(where, "id asc", 1, 10)

	// 直接修改ack状态
	ids := []int{}
	for _,v := range messagea {
		ids = append(ids, v.ID)
	}
	if len(ids) > 0 {
		err = ms.AckArr(ids)
	}

	response.ReturnJsonOk(c, "成功", messagea)
}

